package com.alipay.sofa.award.record.biz.impl.scheduler;

import com.alipay.antschedulerclient.common.ClientCommonResult;
import com.alipay.antschedulerclient.handler.ISimpleJobHandler;
import com.alipay.antschedulerclient.model.JobExecuteContext;
import com.alipay.sofa.award.record.biz.impl.utils.DateFormatUtils;
import com.alipay.sofa.award.record.facade.AwardRecordFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * InvalidAwardRetryThreeTimesHandler
 *
 * @author yangguanchao
 * @since 2018/09/04
 */
public class InvalidAwardRetryThreeTimesHandler implements ISimpleJobHandler {

    private final Logger       logger = LoggerFactory
                                          .getLogger(InvalidAwardRetryThreeTimesHandler.class);

    private ThreadPoolExecutor schedulerThreadPool;

    @Autowired
    private AwardRecordFacade  awardRecordFacade;

    @Override
    public ClientCommonResult handle(JobExecuteContext jobExecuteContext) {
        try {
            Date currentDate = new Date();
            String beforeCurrentDay = DateFormatUtils.getLastDay(currentDate);
            int invalidCount = this.awardRecordFacade.invalidLastDayRecords(beforeCurrentDay);
            logger.info("Invalid last day [" + beforeCurrentDay + "] award code count is "
                        + invalidCount + " on " + currentDate);
            return ClientCommonResult.buildSuccessResult();
        } catch (Exception exception) {
            logger.error("invalidLastDayRecords error!", exception);
            return ClientCommonResult.buildFailResult("invalidLastDayRecords  failed!");
        }
    }

    @Override
    public ThreadPoolExecutor getThreadPool() {
        return this.schedulerThreadPool;
    }

    @Override
    public String getName() {
        return "InvalidAwardRecordRetryThreeTimesHandler";
    }

    public void setSchedulerThreadPool(ThreadPoolExecutor schedulerThreadPool) {
        this.schedulerThreadPool = schedulerThreadPool;
    }
}
